package week_02;

public class IsValidBST_98_2 {

    public class Info {
        boolean isValid;
        Long max;
        Long min;

    }

    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;

        Info info = check(root);

        return info.isValid;
    }

    public Info check(TreeNode root) {
        // 子节点才去返回
        if (root.right == null) {
            Info info = new Info();
            info.isValid = true;
            info.max = Integer.MIN_VALUE - 1L;
            info.min = Integer.MAX_VALUE + 1L;
            return info;
        }

        Info left = check(root.left);
        Info right = check(root.right);
        Info info = new Info();
        info.isValid = left.isValid && right.isValid && left.max < root.val && root.val < right.min;
        info.max = Math.max(Math.max(left.max, right.max), root.val);
        info.min = Math.min(Math.min(left.min, right.min), root.val);
        return info;

    }
}
